import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  ClassSerializerInterceptor,
  Query,
} from '@nestjs/common';
import { Request } from 'express';
import { CompanyService } from './company.service';
import { CreateCompanyDto } from './dto/create-company.dto';
import { UpdateCompanyDto } from './dto/update-company.dto';
import { User } from 'src/auth/decorator/user.decorator';
import { UserEntity } from 'src/user/entities/user.entity';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { ListCompanyDto } from './dto/list-company.dto';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@ApiTags('公司')
@Controller('company')
export class CompanyController {
  constructor(private readonly companyService: CompanyService) {}

  @ApiOperation({ summary: '新增公司' })
  @Post()
  create(@Body() createCompanyDto: CreateCompanyDto, @User() user: UserEntity) {
    if (createCompanyDto.name.length === 0)
      throw new BusinessException('公司名称不能为空');
    if (createCompanyDto.name.length > 255)
      throw new BusinessException('公司名称过长');
    return this.companyService.create(createCompanyDto, user);
  }

  @Get()
  @ApiOperation({ summary: '获取公司列表' })
  @UseInterceptors(ClassSerializerInterceptor)
  findAll(@Query() searchParam: ListCompanyDto, @User() user: UserEntity) {
    return this.companyService.findByPage(searchParam, user);
  }

  @Get('/info/:id')
  findOne(@Param('id') id: string) {
    return this.companyService.findOne(id);
  }

  @Get('/pure')
  getPureList(@User() user: UserEntity) {
    return this.companyService.findAll(user, 'id, name');
  }

  @ApiOperation({ summary: '更新公司' })
  @Patch(':id')
  @UseInterceptors(ClassSerializerInterceptor)
  update(
    @Param('id') id: string,
    @Body() updateCompanyDto: UpdateCompanyDto,
    @User() user: UserEntity,
  ) {
    if (!id || id === '') throw new BusinessException('公司id为空');
    if (updateCompanyDto.name.length === 0)
      throw new BusinessException('公司名称不能为空');
    if (UpdateCompanyDto.name.length > 255)
      throw new BusinessException('公司名称过长');
    return this.companyService.update(id, updateCompanyDto, user);
  }

  @ApiOperation({ summary: '删除公司' })
  @UseInterceptors(ClassSerializerInterceptor)
  @Delete(':id')
  remove(@Param('id') id: string, @User() user: UserEntity) {
    return this.companyService.remove(id, user);
  }
}
